package com.etv.launcher.ui.actvity.splash;

import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.etv.launcher.R;
import com.etv.launcher.common.utils.ToastUtil;
import com.etv.launcher.databinding.FragmentSplashBinding;
import com.etv.launcher.ui.actvity.desktop.DesktopFragment;
import com.etv.launcher.ui.actvity.MainActivityViewModel;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class SplashFragment extends Fragment {

    private final int TIME = 300;

    private FragmentSplashBinding binding;

    private MainActivityViewModel viewModel;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        binding = FragmentSplashBinding.inflate(inflater, container, false);
        viewModel = new ViewModelProvider(requireActivity()).get(MainActivityViewModel.class);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //预加载应用数据
        viewModel.loadApplicationInfo();
        ToastUtil.show(requireContext(),"数据加载完成！");

        //数据加载完成后，跳转页面
        viewModel.getFinishPreInit().observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        FragmentTransaction transaction = requireActivity().getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.root_fragment, new DesktopFragment());
                        transaction.commit();
                    }
                }, TIME);
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}